﻿using Base.Api.Models;
using Common.AspNetCore;
using Common.Infrastructure;
using Common.Infrastructure.Utils;
using Microsoft.Extensions.Configuration;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Base.Api.Service
{
    public class CheckWorkService : CommonService
    {
        private readonly IConfiguration config;

        public CheckWorkService(IServiceProvider provider, IConfiguration c) : base(provider)
        {
            this.config = c;
        }

        /// <summary>
        /// 按工单确认对应的部署站点地址
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<UrlByCheckWorkResultModel> GetUrlByCheckWorkAsync(UrlByCheckWorkParamModel model)
        {
            var mesUrl = this.config["MESURLs"];
            if (string.IsNullOrEmpty(mesUrl) || string.IsNullOrEmpty(model.WorkCode))
            {
                return new UrlByCheckWorkResultModel();
            }

            UrlByCheckWorkResultModel ret = new UrlByCheckWorkResultModel();
            var urls = mesUrl.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var url in urls)
            {
                var rs = await WebApiUtils.PostAsync<ApiActionResult<WorkByCodeModel>>($"{url}/api/Work/Work/GetWorkByCodeModel", new { WorkCode = model.WorkCode?.Trim() });

                if (rs != null && !rs.IsSuccess)
                {
                    rs.Messages.ForEach(t => this.AddError(t.Message));
                }
                else if (rs != null && rs.Data != null && !string.IsNullOrEmpty(rs.Data.Id))
                {
                    ret.Url = url;
                    break;
                }
            }

            if (string.IsNullOrEmpty(ret.Url))
            {
                ret.Url = urls[0];
            }

            return ret;
        }
    }
}
